package Offer.offer;

/**
 * 顺时针打印矩阵
 *
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test20顺时针打印矩阵 {
    public static void main(String[] args) {
        int[][] matrix={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        printMatrix(matrix);
    }

    public static void printMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0
                || matrix[0].length == 0) {
            return;
        }
        int rows = matrix.length;
        int columns = matrix[0].length;

        //确定可以打印几圈
        int start = 0;
        while (rows > 2 * start && columns > 2 * start) {
             printCircle(matrix, start, rows, columns);
             start++;
        }
    }

    private static void printCircle(int[][] matrix, int start, int rows, int columns) {
        int endRow = rows - start - 1;
        int endColumn = columns - start - 1;
        //从左到右打印一行
        for (int i = start; i <= endColumn; i++) {
            System.out.print(matrix[start][i]);
            System.out.print(" ");
        }
        //从上到下打印一列
        if (endRow > start) {
            for (int i = start + 1; i <= endRow; i++) {
                System.out.print(matrix[i][endColumn]);
                System.out.print(" ");
            }
            //从右到左打印一行
            if (endColumn > start) {
                for (int i = endColumn - 1; i >= start ; i--) {
                    System.out.print(matrix[endRow][i]);
                    System.out.print(" ");
                }
                //从下到上打印一列
                if (endRow > start + 1) {
                    for (int i = endRow - 1; i > start ; i--) {
                        System.out.print(matrix[i][start]);
                        System.out.print(" ");
                    }
                }
            }
        }
    }
}
